package org.autocode.controller;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.autocode.code.ColumnInfo;
import org.autocode.code.TableInfo;
import org.autocode.code.template.TemplateHelper;
import org.autocode.component.CodeSetting;
import org.autocode.component.CodeView;
import org.autocode.component.IconLabel;
import org.autocode.config.AutoConfig;
import org.autocode.config.AutoConfigFactory;
import org.autocode.config.DatasourceConfig;
import org.autocode.util.JdbcHelper;
import org.autocode.util.ObjectUtils;
import org.autocode.watch.DatasourceData;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.ResourceBundle;

/**
 * @program: autocode
 * @description:
 * @author: zhu.xiaojie
 * @create: 2020-08-15 18:58
 */
public class MainController implements Initializable {

    @FXML
    public TreeView tree;
    @FXML
    public CodeView codeSql;
    @FXML
    public CodeView codeEntity;
    @FXML
    public CodeView codeDao;
    @FXML
    public CodeSetting setting;


    public MainController() {
    }


    @FXML
    public void gen(ActionEvent event){
        Stage stage = new Stage();
        GridPane gridPane = new GridPane();
        Scene scene = new Scene(gridPane , 400 , 400);
        stage.setScene(scene);
        stage.initModality(Modality.APPLICATION_MODAL);

        stage.show();

/*        DialogPane dialogPane = new DialogPane();
        dialogPane.setContent(new Button("123"));

        Dialog dialog = new Dialog();
        dialog.setDialogPane(dialogPane);
        dialog.show();*/
    }

    @FXML
    public void close(ActionEvent event){
        System.out.println("123");
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        loadTree();

        DatasourceData datasourceData = DatasourceData.getInstance();
        datasourceData.addObserver(new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                loadTree();
            }
        });
    }

    private void loadTree(){

        AutoConfig autoConfig = AutoConfigFactory.getAutoConfig();
        List<DatasourceConfig> datasourceConfigs = autoConfig.getDatasourceConfig();
        if(!ObjectUtils.isEmpty(datasourceConfigs)){
            TreeItem root = new TreeItem("数据源");
            root.setExpanded(true);

            for (DatasourceConfig datasourceConfig : datasourceConfigs) {

                IconLabel iconLabel = new IconLabel();
                iconLabel.setText(datasourceConfig.getName());
                iconLabel.setType(IconLabel.Type.INSTANCE);
                try(InputStream in = this.getClass().getClassLoader().getResourceAsStream("img/mysql.png")){
                    iconLabel.setIcon(in);
                }catch (Exception e){
                    e.printStackTrace();
                }
                TreeItem item = new TreeItem(iconLabel);

                root.getChildren().addAll(item);

            }

            this.tree.setRoot(root);
            this.tree.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if(event.getClickCount() == 2){

                        TreeItem selectedItem = (TreeItem) tree.getSelectionModel().getSelectedItem();
                        IconLabel value = (IconLabel) selectedItem.getValue();
                        String name = value.getText();

                        if(IconLabel.Type.INSTANCE.equals(value.getType())){
                            loadDatabase(selectedItem , name);
                        }else if(IconLabel.Type.DATABASE.equals(value.getType())){
                            // 加载表
                            loadTables(selectedItem , name);
                        }else if(IconLabel.Type.TABLE.equals(value.getType())){
                            // 表的点击事件
                            TreeItem parent = selectedItem.getParent();
                            TreeItem insParent = parent.getParent();

                            IconLabel instanceLabel = (IconLabel)insParent.getValue();
                            String instance = instanceLabel.getText();

                            IconLabel databaseLabel = (IconLabel) parent.getValue();
                            String database = databaseLabel.getText();


                            loadTableInfo(instance , database , value.getText());
                        }





                    }
                }
            });
        }

    }


    private void loadTableInfo(String instance , String database , String table){
        AutoConfig autoConfig = AutoConfigFactory.getAutoConfig();
        DatasourceConfig config = autoConfig.getDatasourceConfigByName(instance);


        TableInfo tableInfo = JdbcHelper.getTableInfo(config, database, table);
        System.out.println(tableInfo);

        TemplateHelper templateHelper = TemplateHelper.getInstance();

        this.codeSql.setText("sql" , tableInfo.getSql());
        this.codeEntity.setText("java" , tableInfo.getJavaPO());
        ColumnInfo columnInfo = new ColumnInfo();
        columnInfo.setColumnType(4);
        columnInfo.setColumnName("userId");
        columnInfo.setColumnComment("你好");
        this.codeDao.setText("java" , templateHelper.genDaoCode(tableInfo , columnInfo));

    }



    private void loadTables(TreeItem selectedItem , String database){
        TreeItem parent = selectedItem.getParent();
        IconLabel parentIconLabel = (IconLabel) parent.getValue();
        String instanceName = parentIconLabel.getText();

        AutoConfig autoConfig = AutoConfigFactory.getAutoConfig();

        List<String> tables = JdbcHelper.listTable(autoConfig.getDatasourceConfigByName(instanceName), database);
        if(!ObjectUtils.isEmpty(tables)){
            for (String table : tables) {
                IconLabel iconLabel = new IconLabel();
                iconLabel.setType(IconLabel.Type.TABLE);
                iconLabel.setText(table);
                iconLabel.setIcon("img/table.png");

                TreeItem item = new TreeItem(iconLabel);
                selectedItem.getChildren().add(item);
            }
        }


    }

    private void loadDatabase(TreeItem selectedItem , String name){
        AutoConfig autoConfig = AutoConfigFactory.getAutoConfig();
        DatasourceConfig config = autoConfig.getDatasourceConfigByName(name);

        try {
            List<String> databases = JdbcHelper.listDatabase(config);

            for (String database : databases) {

                IconLabel iconLabel = new IconLabel();
                iconLabel.setText(database);
                iconLabel.setType(IconLabel.Type.DATABASE);
                try(InputStream in = this.getClass().getClassLoader().getResourceAsStream("img/database.png")){
                    iconLabel.setIcon(in);
                }catch (Exception e){
                    e.printStackTrace();
                }



                TreeItem item = new TreeItem(iconLabel);

                selectedItem.getChildren().add(item);
            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @FXML
    public void openAddDatasource(ActionEvent event) throws IOException {
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("fxml/AddDatasource.fxml"));
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.setTitle("新增数据源");

        Scene scene = new Scene(root , 300 , 300);

        stage.setScene(scene);

        stage.show();
    }
}
